package com.imodia.checkoo.thread.htmlInfo;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hsq.commons.util.DateUtil;
import com.hsq.commons.util.NewsContentUtil;
import com.hsq.commons.util.db.SqlParam;
import com.hsq.commons.util.file.FileUtil;
import com.imodia.checkoo.bean.CmsArticleBean;
import com.imodia.checkoo.service.CmsArticleService;

public class NewsTaskExecutorHtml extends TaskExecutorHtml {

	private static Log log = LogFactory.getLog(NewsTaskExecutorHtml.class);

	private CmsArticleService cmsArticleService;

	public void setCmsArticleService(CmsArticleService cmsArticleService) {
		this.cmsArticleService = cmsArticleService;
	}

	public void htmlNewsById(int id) {
		log.debug("________html news by id_____");
		if (!checkData()) {
			return;
		}
		CmsArticleBean siteNews = cmsArticleService.get(id);
		if (siteNews != null)
			html4news(siteNews);
	}

	public void htmlNews() {
		if (!checkData()) {
			return;
		}
		List<CmsArticleBean> list = cmsArticleService.list(new SqlParam());
		for (int i = 0; i < list.size(); i++) {
			CmsArticleBean siteNews = list.get(i);
			html4news(siteNews);
		}
	}

	public void html4news(CmsArticleBean news) {
		log.debug("________htmlUrl:" + news.getHtmlUrl());
		String dir = "";
		if (news.getHtmlUrl() == null || news.getHtmlUrl().trim().length() <= 0
				|| !news.getHtmlUrl().endsWith(".html")) {
			Date date = new Date();
			dir = "/news/" + DateUtil.parseYYYY(date) + "/"	+ DateUtil.parseMM(date) + "/" + DateUtil.parseDD(date);
			FileUtil.mkdir(realPath + dir);
			news.setHtmlUrl(dir + "/" + DateUtil.parseHHMMSS(date) + "A"+ news.getId() + ".html");
			int x = cmsArticleService.updateHtml(news.getHtmlUrl(), news.getId());
			log.debug("________x:" + x);
		}

		String isExistPath = realPath + news.getHtmlUrl().substring(0,news.getHtmlUrl().lastIndexOf("/"));
		FileUtil.mkdir(isExistPath);

		int contentIds = NewsContentUtil.getContentCount(news.getContent());

		if (news.getIsValidate() == 0) {
			FileUtil.delete(realPath + news.getHtmlUrl());
			for (int i = 1; i <= contentIds; i++) {
				String htmlurl = news.getHtmlUrl();
				if (i > 1) {
					htmlurl = news.getHtmlUrl().replaceAll(".html",	"_" + i + ".html");
					FileUtil.delete(realPath + htmlurl);
				}
			}
		} else {
			for (int i = 1; i <= contentIds; i++) {
				String htmlurl = news.getHtmlUrl();
				if (i > 1) {
					htmlurl = news.getHtmlUrl().replaceAll(".html",
							"_" + i + ".html");
				}
				taskExecutor.execute(new ThreadTaskExecutorHtml(siteUrl
						+ news.getDynamicUrl() + "&contentId=" + i
						+ "&isHtml=1", realPath + htmlurl));
			}
		}

	}

}
